package cn.kgc.itrip.biz.service.impl;

import cn.kgc.itrip.beans.common.ServerResponse;
import cn.kgc.itrip.beans.model.pojo.*;
import cn.kgc.itrip.beans.model.vo.order.*;
import cn.kgc.itrip.biz.service.ItripHotelOrderService;
import cn.kgc.itrip.mapper.itripHotel.ItripHotelMapper;
import cn.kgc.itrip.mapper.itripHotelOrder.ItripHotelOrderMapper;
import cn.kgc.itrip.mapper.itripHotelRoom.ItripHotelRoomMapper;
import cn.kgc.itrip.mapper.itripProductStore.ItripProductStoreMapper;
import cn.kgc.itrip.mapper.itripUserLinkUser.ItripUserLinkUserMapper;
import cn.kgc.itrip.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 阿泽
 */
@Service("itripHotelOrderService")
@Slf4j
public class ItripHotelOrderServiceImpl implements ItripHotelOrderService {

    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;
    @Resource
    private RedisApi redisApi;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ItripHotelMapper itripHotelMapper;
    @Resource
    private ItripHotelRoomMapper itripHotelRoomMapper;
    @Resource
    private ItripProductStoreMapper itripProductStoreMapper;
    @Resource
    private ItripUserLinkUserMapper itripUserLinkUserMapper;

    /**
     * @param validateRoomStoreVo
     * @return
     */

    @Override
    public ServerResponse validateroomstore(ValidateRoomStoreVO validateRoomStoreVo) {
        ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
        itripHotelOrder.setCheckInDate(validateRoomStoreVo.getCheckInDate());
        itripHotelOrder.setCount(validateRoomStoreVo.getCount());
        itripHotelOrder.setCheckOutDate(validateRoomStoreVo.getCheckOutDate());
        itripHotelOrder.setHotelId(Long.valueOf(validateRoomStoreVo.getHotelId()));
        itripHotelOrder.setRoomId(Long.valueOf(validateRoomStoreVo.getRoomId()));
        try {
            Integer integer = itripHotelOrderMapper.updateItripHotelOrder(itripHotelOrder);
            if (integer < 0) {
                return ServerResponse.createByErrorMessage("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess();
    }

    /**
     * 根据订单ID查看个人订单详情
     *
     * @param orderId
     * @return
     */

    @Override
    public ServerResponse getpersonalorderinfo(Integer orderId) {
        if (orderId == null || orderId == 0) {
            log.error("根据订单ID查看个人订单详情时发生了参数丢失");
            return ServerResponse.createByErrorMessage("必须传递订单号");
        }
        itripOrderDatailVo itripOrderDatailVo = itripHotelOrderMapper.queryOrderinfo(orderId);
        //订单取消
        if (itripOrderDatailVo.getOrderStatus() == 1) {
            itripOrderDatailVo.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessCancel()));
            itripOrderDatailVo.setProcessNode("3");
        }
        if (itripOrderDatailVo.getOrderStatus() == 0) {
            itripOrderDatailVo.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripOrderDatailVo.setProcessNode("2");
        }
        if (itripOrderDatailVo.getOrderStatus() == 2) {
            itripOrderDatailVo.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripOrderDatailVo.setProcessNode("4");
        }
        if (itripOrderDatailVo.getOrderStatus() == 3) {
            itripOrderDatailVo.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripOrderDatailVo.setProcessNode("5");
        }
        if (itripOrderDatailVo.getOrderStatus() == 4) {
            itripOrderDatailVo.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripOrderDatailVo.setProcessNode("6");
        }
        return ServerResponse.createBySuccess("查询个人订单成功", itripOrderDatailVo);
    }

    /**
     * 根据个人订单列表，并分页显示
     *
     * @return
     */
    @Override
    public ServerResponse getpersonalorderlist(itripSearchOrderVo itripSearchOrderVO, String token) {
        log.info("获取用户订单列表");
        if (StringUtils.isBlank(token)) {
            log.error("获取用户订单列表:没有获取token" + token);
            return ServerResponse.createByErrorMessage("请登入");
        }
        if (!redisApi.exists(token)) {
            log.error("获取用户订单列表:获取token失效" + token);
            return ServerResponse.createByErrorMessage("token失效");
        }
        //从redisApi中获取用户信息
        ItripUser itripUser = JSONObject.parseObject(redisApi.get(token), ItripUser.class);

        System.out.println(itripUser.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("endDate", itripSearchOrderVO.getEndDate());
        map.put("linkUserName", itripSearchOrderVO.getLinkUserName());
        map.put("orderNo", itripSearchOrderVO.getOrderNo());
        map.put("orderStatus", itripSearchOrderVO.getOrderStatus());
        map.put("orderType", itripSearchOrderVO.getOrderType());
        map.put("startDate", itripSearchOrderVO.getStartDate());
        //TODO pageSize pageNo 需要计算
        map.put("userId", itripUser.getId());
        //计算当前总条数
        System.out.println("查询成功");
        Integer rowCount = itripHotelOrderMapper.queryHotelOrderCount(map);
        Page page = new Page(
                itripSearchOrderVO.getPageNo() == null ? 1 : itripSearchOrderVO.getPageNo()
                , itripSearchOrderVO.getPageSize() == null ? 6 : itripSearchOrderVO.getPageSize(), rowCount);
        map.put("pageNo", page.getBeginPos());
        map.put("pageSize", page.getPageSize());
        log.info("获取用户列表 查询订单列表完成");
        List<itripOrderListVo> getpersonalorderlist = itripHotelOrderMapper.getpersonalorderlist(map);
        log.info(getpersonalorderlist.toString());
        page.setRows(getpersonalorderlist);
        return ServerResponse.createBySuccess("查询列表成功", page);
    }

    /**
     * 根据订单ID查看个人订单详情-房型相关信息
     *
     * @param orderId
     * @return
     */
    @Override
    public ServerResponse getpersonalorderroominfo(Integer orderId) {
        log.info("查看个人订单详情-房型相关信息");

        if (orderId == null || orderId == 0) {
            log.error("查询订单房间详情【错误】:参数丢失");
            return ServerResponse.createByErrorMessage("订单id不能为空");
        }
        OrderRomDatailVo orderRomDatailVo = itripHotelOrderMapper.queryOrderRoomDetail(orderId);
        return ServerResponse.createBySuccess("查看订单详情成功", orderRomDatailVo);
    }

    /**
     * 修改订单状态 任务调度 用
     *
     * @param type
     */
    @Override
    public void updateOrderStatus(Integer type) {

        if (type == 1) {
            Integer integer = itripHotelOrderMapper.updateOrderStatusByCancel();
            log.info("任务调度执行完成未支付的订单数为" + integer);
        } else {
            Integer integer = itripHotelOrderMapper.updateOrderBySuccess();
            log.info("任务调度执行完成已消费的订单数为" + integer);
        }
    }

    @Override
    public ServerResponse queryStore(ValidateRoomStoreVO validateRoomStoreVo, String token) {

        System.out.println("酒店Id" + validateRoomStoreVo.getHotelId());
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("请登录！");
        }
        if (!redisApi.exists(token)) {
            return ServerResponse.createByErrorMessage("token失效,请重新登录");
        }
        //刷新库存表
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", validateRoomStoreVo.getCheckInDate());
        map.put("endTime", validateRoomStoreVo.getCheckOutDate());
        map.put("hotelId", validateRoomStoreVo.getHotelId());
        map.put("roomId", validateRoomStoreVo.getRoomId());
        itripHotelOrderMapper.flashStore(map);
        //TODO 获取酒店房间信息
        ItripHotelRoom itripHotelRoomById = itripHotelRoomMapper.getItripHotelRoomById(validateRoomStoreVo.getRoomId());

        System.out.println("没走这一步操作");
        //TODO 获取酒店信息
        ItripHotel itripHotel = itripHotelMapper.queryHotel(validateRoomStoreVo.getHotelId());

        map.put("checkInDate", validateRoomStoreVo.getCheckInDate());
        map.put("checkOutDate", validateRoomStoreVo.getCheckOutDate());
        map.put("roomId", validateRoomStoreVo.getRoomId());
        itripRoomStore itripRoomStore = itripHotelOrderMapper.queryRoomStore(map);

        StoreInfoVo storeInfoVo = new StoreInfoVo();
        storeInfoVo.setCheckInDate(validateRoomStoreVo.getCheckInDate());
        storeInfoVo.setCheckOutDate(validateRoomStoreVo.getCheckOutDate());
        storeInfoVo.setCount(validateRoomStoreVo.getCount());
        storeInfoVo.setHotelId(itripHotel.getId());
        storeInfoVo.setPrice(itripHotelRoomById.getRoomPrice());
        storeInfoVo.setHotelName(itripHotel.getHotelName());
        if (itripRoomStore == null) {
            //TODO 查询原始库存表
            storeInfoVo.setStore(itripProductStoreMapper.queryProductStore(validateRoomStoreVo.getRoomId()));
        } else {
            storeInfoVo.setRoomId(itripRoomStore.getRoomId());
            storeInfoVo.setStore(itripRoomStore.getStore());
        }
        return ServerResponse.createBySuccess(storeInfoVo);

    }

    @Override
    public ServerResponse addhotelorder(ItripAddHotelOrderVO itripAddHotelOrderVO, String token) {
        log.info("生成订单");
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("请登录！");
        }
        if (!redisApi.exists(token)) {
            return ServerResponse.createByErrorMessage("token失效,请重新登录");
        }
        //获取用户对象
        ItripUser itripUser = JSON.parseObject(redisApi.get(token), ItripUser.class);

        //刷新库存表
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", itripAddHotelOrderVO.getCheckInDate());
        map.put("endTime", itripAddHotelOrderVO.getCheckOutDate());
        map.put("hotelId", itripAddHotelOrderVO.getHotelId());
        map.put("roomId", itripAddHotelOrderVO.getRoomId());
        itripHotelOrderMapper.flashStore(map);
        //验证是否有房间
        map.put("checkInDate", itripAddHotelOrderVO.getCheckInDate());
        map.put("checkOutDate", itripAddHotelOrderVO.getCheckOutDate());
        map.put("hotelId", itripAddHotelOrderVO.getHotelId());
        itripRoomStore itripRoomStore = itripHotelOrderMapper.queryRoomStore(map);
        if (itripRoomStore != null) {
            if (itripRoomStore.getStore() < itripAddHotelOrderVO.getCount()) {
                log.error("生成订单【错误】库存不足");
                return ServerResponse.createBySuccessMessage("库存不足");
            }
        }
        ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
        //生成 订单号

        StringBuffer order = new StringBuffer();
        order.append("D1000001")
                .append(itripAddHotelOrderVO.getRoomId())
                .append(System.currentTimeMillis())
                .append(StringUtils.substring(MD5Util.MD5EncodeUtf8(itripAddHotelOrderVO.getNoticePhone()), 3, 7));
        //生成交易编号
        StringBuffer tradeNo = new StringBuffer();
        tradeNo.append(System.currentTimeMillis()).append(itripAddHotelOrderVO.getRoomId()).append((int) Math.random() * 10);
        //判断是什么设备下的单
        String flag = StringUtils.substring(token, 6, 7);

        if (flag.equals("P")) {
            itripHotelOrder.setBookType(0);
        } else if (flag.equals("M")) {
            itripHotelOrder.setBookType(1);
        } else {
            itripHotelOrder.setBookType(2);
        }
        //计算价格

        ItripHotelRoom itripHotelRoomById = itripHotelRoomMapper.getItripHotelRoomById(itripAddHotelOrderVO.getRoomId());

        BigDecimal totalMoney = BigDecimalUtil.mul(itripAddHotelOrderVO.getCount(), itripHotelRoomById.getRoomPrice());
        double valueMoney = totalMoney.doubleValue();
        BeanUtils.copyProperties(itripAddHotelOrderVO, itripHotelOrder);
        StringBuffer sb = new StringBuffer();
        for (ItripUserLinkUser itripUserLinkUser : itripAddHotelOrderVO.getLinkUser()) {
            sb.append(itripUserLinkUser.getLinkUserName());
        }
        itripHotelOrder.setBookingDays(DateUtil.getBetweenDates(itripAddHotelOrderVO.getCheckInDate(), itripAddHotelOrderVO.getCheckOutDate()).size() - 1);

        itripHotelOrder.setPayAmount(valueMoney);
        itripHotelOrder.setLinkUserName(sb.toString());
        itripHotelOrder.setOrderStatus(0);
        itripHotelOrder.setTradeNo(tradeNo.toString());
        itripHotelOrder.setOrderNo(order.toString());
        itripHotelOrder.setCreatedBy(itripUser.getId());
        itripHotelOrder.setUserId(itripUser.getId());
        Integer integer = itripHotelOrderMapper.insertItripHotelOrder(itripHotelOrder);
        if (integer < 0) {
            return ServerResponse.createBySuccessMessage("插入失败");
        }
        AddOrderSuccessVo addOrderSuccessVo = new AddOrderSuccessVo();
        addOrderSuccessVo.setId(itripHotelOrder.getId());
        addOrderSuccessVo.setOrder(order.toString());
        return ServerResponse.createBySuccess("生成订单成功", addOrderSuccessVo);
    }

    /**
     * 根据订单ID获取订单信息
     *
     * @param orderId
     * @param request
     * @return
     */
    @Override
    public ServerResponse queryOrderById(Long orderId, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("请登录！");
        }
        if (!redisApi.exists(token)) {
            return ServerResponse.createByErrorMessage("token失效,请重新登录");
        }
        //封装返回对象
        ItripPersonalHotelOrderVO itripPersonalHotelOrderVO = new ItripPersonalHotelOrderVO();
        //根据orderId查询订单
        ItripHotelOrder order = itripHotelOrderMapper.getItripHotelOrderById(orderId);

        if (order == null) {
            return ServerResponse.createByErrorMessage("没有该订单");
        }
//封装订单id
        itripPersonalHotelOrderVO.setId(order.getId());
        //封装预定方式
        itripPersonalHotelOrderVO.setBookType(order.getBookType());
        //封装订单时间
        itripPersonalHotelOrderVO.setCreationDate(order.getCreationDate());
        //封装订单号
        itripPersonalHotelOrderVO.setOrderNo(order.getOrderNo());
        //查询预定房间信息、
        ItripHotelRoom itripHotelRoomById = itripHotelRoomMapper.getItripHotelRoomById(order.getRoomId());
        itripPersonalHotelOrderVO.setRoomPayType(itripHotelRoomById.getPayType());

//封装订单状态
        //订单状态（0：待支付 1:已取消 2:支付成功 3:已消费 4:已点评）
        //{"1":"订单提交","2":"订单支付","3":"支付成功","4":"入住","5":"订单点评","6":"订单完成"}
        //{"1":"订单提交","2":"订单支付","3":"订单取消"}

        Integer orderStatus = order.getOrderStatus();
        itripPersonalHotelOrderVO.setOrderStatus(orderStatus);

        //订单取消
        if (orderStatus == 1) {
            itripPersonalHotelOrderVO.setOrderProcess
                    (JSONArray.parse(systemConfig.getOrderProcessCancel()));
            itripPersonalHotelOrderVO.setProcessNode("3");
        }
        //待支付
        else if (orderStatus == 0) {
            itripPersonalHotelOrderVO.setOrderProcess
                    (JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripPersonalHotelOrderVO.setProcessNode("2");
        }
        //支付成功
        else if (orderStatus == 2) {
            itripPersonalHotelOrderVO.setOrderProcess
                    (JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripPersonalHotelOrderVO.setProcessNode("3");
        }
        //以消费
        else if (orderStatus == 3) {
            itripPersonalHotelOrderVO.setOrderProcess
                    (JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripPersonalHotelOrderVO.setProcessNode("5");
        }
        //已点评
        else if (orderStatus == 4) {
            itripPersonalHotelOrderVO.setOrderProcess
                    (JSONArray.parse(systemConfig.getOrderProcessOK()));
            itripPersonalHotelOrderVO.setProcessNode("6");
        } else {
            itripPersonalHotelOrderVO.setOrderProcess(null);
            itripPersonalHotelOrderVO.setProcessNode(null);
        }
        itripPersonalHotelOrderVO.setPayAmount(order.getPayAmount());
        itripPersonalHotelOrderVO.setPayType(order.getPayType());
        itripPersonalHotelOrderVO.setNoticePhone(order.getNoticePhone());

        return ServerResponse.createBySuccess(itripPersonalHotelOrderVO);
    }


    /**
     * 线下支付   修改订单状态
     * @param itripModifyHotelOrderVO
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse updateOrderStatusAndPayType(ItripModifyHotelOrderVO itripModifyHotelOrderVO, HttpServletRequest request)throws Exception
    {
        String token =  request.getHeader("token");
        if(!redisApi.exists(token))
        {
            return ServerResponse.createByErrorMessage("token失效，请重新登录");
        }

        //验证是否支持线下支付服务
        Integer patTypeByHotelId = itripHotelOrderMapper.getPatTypeByHotelId(itripModifyHotelOrderVO.getId());
        if(!((2&patTypeByHotelId)!=0))
        {
            return ServerResponse.createByErrorMessage("对不起，此房间不支持线下支付");
        }
        ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
        itripHotelOrder.setId(itripModifyHotelOrderVO.getId());
        //设置支付类型
        itripHotelOrder.setPayType(3);
        //支付成  2 已支付
        itripHotelOrder.setOrderStatus(2);
        ItripUser itripUser = JSON.parseObject(redisApi.get(request.getHeader("token")), ItripUser.class);
        //修改人信息
        itripHotelOrder.setModifiedBy(itripUser.getId());
        itripHotelOrder.setModifyDate(new Date());

        itripHotelOrderMapper.updateItripHotelOrder(itripHotelOrder);

        return ServerResponse.createBySuccess();
    }


}